﻿using BaseDll;
using CommonTools;
using MotionIoLib;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using UserCtrl;

namespace StationDemo
{
    public partial class Form_IO : UIPage
    {
        public Form_IO()
        {
            InitializeComponent();
        }
        UserIoInput[] m_IoInputs;
        UserIOOutPut[] m_IoOutputs;
        private void Form_IO_Load(object sender, EventArgs e)
        {
            iniInput();
            iniOutput();

            UpDataAllIo();
            IOMgr.GetInstace().m_eventIoInputChanage += ChangedIoInState;
            IOMgr.GetInstace().m_eventIoOutputChanage += ChangedIoOutState;

            Language.LanguageHelp.GetInstance().Funtion_TransLate(this.Name);
            sys.g_eventRightChanged += ChangedUserRight;
            ChangedUserRight(sys.g_User);
            GlobalVariable.g_eventStationStateChanged += GlobalVariable_g_eventStationStateChanged;
            GlobalVariable.g_eventControlModeChanged += GlobalVariable_g_eventControlModeChanged;

            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }
        private void GlobalVariable_g_eventControlModeChanged(ControlMode currRunMode)
        {
            GlobalVariable_g_eventStationStateChanged(GlobalVariable.g_StationState);
        }

        private void GlobalVariable_g_eventStationStateChanged(StationState currState)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => GlobalVariable_g_eventStationStateChanged(currState)));
            else
            {
                if ((int)sys.g_User._userRight >= (int)UserRight.Debug && GlobalVariable.g_StationState != StationState.StationStateRun)
                {
                    foreach (var temp in tabInput.Controls)
                    {
                        ((Control)temp).Enabled = true;
                    }
                    foreach (var temp in tabOutput.Controls)
                    {
                        ((Control)temp).Enabled = true;
                    }
                }
                else
                {
                    foreach (var temp in tabInput.Controls)
                    {
                        ((Control)temp).Enabled = false;
                    }
                    foreach (var temp in tabOutput.Controls)
                    {
                        ((Control)temp).Enabled = false;
                    }
                }
            }
        }
        void iniOutput()
        {
            int outputNum = IOMgr.GetInstace().GetIoOutputNum();
            m_IoOutputs = new UserIOOutPut[outputNum];
            Dictionary<string, IOMgr.IoDefine> dicOutput = IOMgr.GetInstace().GetOutputDic();//所有输出点字典
            List<string> pages = new List<string>(); //页名集合

            #region 获取每页最长名称
            Dictionary<string, string> pageMaxLengthDic = new Dictionary<string, string>();//每页最长字符<页名称，IO名称>
            foreach (var key in dicOutput.Keys)
            {
                if (dicOutput[key].PageName != null && dicOutput[key].PageName != "" && !pages.Contains(dicOutput[key].PageName))
                {
                    pages.Add(dicOutput[key].PageName);
                }
                if (dicOutput[key].PageName != null && dicOutput[key].PageName != "" && !pageMaxLengthDic.ContainsKey(dicOutput[key].PageName))
                    pageMaxLengthDic.Add(dicOutput[key].PageName, key);
                if (dicOutput[key].PageName != null && dicOutput[key].PageName != "" && pageMaxLengthDic[dicOutput[key].PageName].Length < key.Length)
                {
                    pageMaxLengthDic[dicOutput[key].PageName] = key;
                }
            }
            #endregion

            #region 获取页名查找页面的字典
            Dictionary<string, TabPage> pageDic = new Dictionary<string, TabPage>();
            tabOutput.TabPages.Clear();
            if (pages.Count > 0)
            {
                foreach (var sPage in pages)
                {
                    TabPage uiPage = new TabPage { Text = sPage };
                    tabOutput.TabPages.Add(uiPage);
                    pageDic.Add(sPage, uiPage);
                }
            }
            #endregion

            #region 将IO添加到对应的分页容器
            int panWidth = tabOutput.Width - tabOutput.ItemSize.Width;
            int index = 0;

            foreach (var item in dicOutput)
            {
                UserIOOutPut output = new UserIOOutPut();
                output.IOName = item.ToString();
                m_IoOutputs[index++] = output;
            }
            foreach (var uiPage in pageDic)
            {
                //int nextLeft = 0;
                //int nextTop = 0;
                int top = 0;
                int left = 0;
                int maxLength = GetMaxOutputLength(pageMaxLengthDic, uiPage);//获取最长IO长度作为列宽
                foreach (var item in dicOutput)
                {
                    if (uiPage.Key == item.Value.PageName)
                    {
                        UserIOOutPut output = m_IoOutputs.First((t) => t.IOName == item.ToString());
                        pageDic[item.Value.PageName].Controls.Add(output);
                        output.IOName = item.Key;
                        output.Height = 40;
                        output.State = false;
                        output.OnColor = Color.Green;
                        output.OffColor = Color.Gray;
                        output.StateChanged += Output_Click;
                        if (left + maxLength > panWidth)
                        {
                            left = 0;
                            top += output.Height;
                        }
                        output.Left = left;
                        output.Top = top;
                        left += maxLength;
                    }
                }
            }
            #endregion
        }

        private void Output_Click(string ioName, bool state)
        {
            string strIOName = Language.LanguageHelp.GetInstance().Function_TransToChinese(this.Name, ioName);
            bool bState = IOMgr.GetInstace().ReadIoOutBit(strIOName);
            IOMgr.GetInstace().WriteIoBit(ioName, !bState);
        }

        private int GetMaxOutputLength(Dictionary<string, string> pageMaxLengthDic, KeyValuePair<string, TabPage> uiPage)
        {
            string maxLengthIo = pageMaxLengthDic[uiPage.Key];
            UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = maxLengthIo };
            return tmpOutPut.Width + 50;
        }

        private int GetMaxInputLength(Dictionary<string, string> pageMaxLengthDic, KeyValuePair<string, TabPage> uiPage)
        {
            string maxLengthIo = pageMaxLengthDic[uiPage.Key];
            UserIOOutPut tmpOutPut = new UserIOOutPut { IOName = maxLengthIo };
            return tmpOutPut.Width + 50;
        }
        void iniInput()
        {
            int inputNum = IOMgr.GetInstace().GetIoInputNum();
            m_IoInputs = new UserIoInput[inputNum];
            Dictionary<string, IOMgr.IoDefine> dicInput = IOMgr.GetInstace().GetInputDic();//所有输出点字典
            List<string> pages = new List<string>(); //页名集合

            #region 获取每页最长名称
            Dictionary<string, string> pageMaxLengthDic = new Dictionary<string, string>();//每页最长字符<页名称，IO名称>
            int nIndex = 0;
            foreach (var key in dicInput.Keys)
            {
                nIndex++;
                if (dicInput[key].PageName != null && dicInput[key].PageName != "" && !pages.Contains(dicInput[key].PageName))
                {
                    pages.Add(dicInput[key].PageName);
                }

                if (dicInput[key].PageName != null && dicInput[key].PageName != "" && !pageMaxLengthDic.ContainsKey(dicInput[key].PageName))
                    pageMaxLengthDic.Add(dicInput[key].PageName, key);
                if (dicInput[key].PageName != null && dicInput[key].PageName != "" && pageMaxLengthDic[dicInput[key].PageName].Length < key.Length)
                {
                    pageMaxLengthDic[dicInput[key].PageName] = key;
                }
            }
            #endregion

            #region 获取页名查找页面的字典
            Dictionary<string, TabPage> pageDic = new Dictionary<string, TabPage>();
            tabInput.TabPages.Clear();
            if (pages.Count > 0)
            {
                foreach (var sPage in pages)
                {
                    TabPage uiPage = new TabPage { Text = sPage };
                    tabInput.TabPages.Add(uiPage);
                    pageDic.Add(sPage, uiPage);
                }
            }
            #endregion

            #region 将IO添加到对应的分页容器
            int panWidth = tabInput.Width - tabInput.ItemSize.Width;
            int index = 0;
            foreach (var item in dicInput)
            {
                UserIoInput input = new UserIoInput();
                input.IOName = item.ToString();
                m_IoInputs[index++] = input;
            }
            foreach (var uiPage in pageDic)
            {
                int top = 0;
                int left = 0;
                int maxLength = GetMaxInputLength(pageMaxLengthDic, uiPage);//获取最长IO长度作为列宽
                foreach (var item in dicInput)
                {
                    if (uiPage.Key == item.Value.PageName)
                    {
                        UserIoInput input = m_IoInputs.First((t) => t.IOName == item.ToString());
                        pageDic[item.Value.PageName].Controls.Add(input);

                        input.IOName = item.Key;
                        input.Height = 40;
                        input.State = true;
                        input.OnColor = Color.Green;
                        input.OffColor = Color.Gray;
                        if (left + maxLength > panWidth)
                        {
                            left = 0;
                            top += input.Height;
                        }
                        input.Left = left;
                        input.Top = top;
                        left += maxLength;
                    }
                }
            }
            #endregion
        }

        public void ChangedUserRight(User CurrentUser)
        {
            if (InvokeRequired)
                this.BeginInvoke(new Action(() => ChangedUserRight(CurrentUser)));
            else
            {
                if ((int)CurrentUser._userRight >= (int)UserRight.Debug && GlobalVariable.g_StationState != StationState.StationStateRun)
                {
                    foreach (var temp in tabInput.Controls)
                    {
                        ((Control)temp).Enabled = true;
                    }
                    foreach (var temp in tabOutput.Controls)
                    {
                        ((Control)temp).Enabled = true;
                    }
                }
                else
                {
                    foreach (var temp in tabInput.Controls)
                    {
                        ((Control)temp).Enabled = false;
                    }
                    foreach (var temp in tabOutput.Controls)
                    {
                        ((Control)temp).Enabled = false;
                    }
                }
            }
        }

        private void Form_IO_Resize(object sender, EventArgs e)
        {
            panInput.Width = (Width + 2) / 2;
            panOutput.Width = (Width + 2) / 2;
        }

        private void Form_IO_VisibleChanged(object sender, EventArgs e)
        {

        }
        public void UpDataAllIo()
        {
            Dictionary<string, IOMgr.IoDefine> dicInput = IOMgr.GetInstace().GetInputDic();
            int indexIn = 0;
            foreach (var tem in dicInput)
            {
                m_IoInputs[indexIn++].State = IOMgr.GetInstace().ReadIoInBit(tem.Key);

            }

            Dictionary<string, IOMgr.IoDefine> dicOutput = IOMgr.GetInstace().GetOutputDic();
            int indexOut = 0;
            foreach (var tem in dicOutput)
                m_IoOutputs[indexOut++].State = IOMgr.GetInstace().ReadIoOutBit(tem.Key);
        }

        public void ChangedIoInState(int index, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoInState(index, bStateCurrent)));
            }
            else
                m_IoInputs[index].State = bStateCurrent;
        }
        public void ChangedIoOutState(int index, bool bStateCurrent)
        {
            if (InvokeRequired)
            {
                this.BeginInvoke(new Action(() => ChangedIoOutState(index, bStateCurrent)));
            }
            else
                m_IoOutputs[index].State = bStateCurrent;
        }

        private void Form_IO_Activated(object sender, EventArgs e)
        {
            if (Visible)
            {
                UpDataAllIo();
                IOMgr.GetInstace().m_eventIoInputChanage += ChangedIoInState;
                IOMgr.GetInstace().m_eventIoOutputChanage += ChangedIoOutState;
            }
            else
            {
                IOMgr.GetInstace().m_eventIoInputChanage -= ChangedIoInState;
                IOMgr.GetInstace().m_eventIoOutputChanage -= ChangedIoOutState;
            }
        }
    }
}
